package com.example.campus_activity_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.campus_activity_backend.common.ErrorCode;
import com.example.campus_activity_backend.domain.SysUser;
import com.example.campus_activity_backend.exception.BusinessException;
import com.example.campus_activity_backend.service.SysUserService;
import com.example.campus_activity_backend.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author Hongxia
* @description 针对表【t_sys_user】的数据库操作Service实现
* @createDate 2023-11-17 14:21:55
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService {

    @Resource
    private SysUserMapper userMapper;

    @Override
    public long addUser(SysUser user) {
        //1.校验参数
        if(StringUtils.isAnyBlank(user.getLoginName(),user.getPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        //2.检查合法性

        //3.检查用户名是否重复
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name",user.getLoginName());
        Integer integer = userMapper.selectCount(queryWrapper);
        if(integer > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名已存在");
        }
        //4.添加用户到数据库
        boolean saveResult = this.save(user);
        if(!saveResult){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户添加失败");
        }
        return user.getId();
    }

    @Override
    public SysUser getSafetyUser(SysUser user) {
        if(user == null){
            return null;
        }
        SysUser safetyUser = new SysUser();
        safetyUser.setId(user.getId());
        safetyUser.setLoginName(user.getLoginName());
        safetyUser.setBirthday(user.getBirthday());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setGender(user.getGender());
        safetyUser.setStatus(user.getStatus());
        return safetyUser;
    }

    @Override
    public SysUser getUserByLoginName(String loginName) {
        if(loginName == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名为空");
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name",loginName);
        SysUser user = userMapper.selectOne(queryWrapper);
        //用户脱敏
        SysUser safetyUser = this.getSafetyUser(user);
        return safetyUser;
    }


}




